<template>
  <div class="app-header">
    <!-- 左侧：主页和头像 -->
    <div class="header-left">
      <router-link to="/" class="home-link">
        <el-icon><HomeFilled /></el-icon>
      </router-link>
      <div class="app-avatar" @click="openEditDialog">
        <el-avatar :size="36" :src="appData.BaseConfig.Avatar" />
      </div>
      <div class="app-info">
        <div class="app-name">{{ appData.BaseConfig.Name }}</div>
        <div class="app-mode">标准模式</div>
      </div>
    </div>

    <!-- 中间：导航菜单 -->
    <div class="header-center">
      <router-link
        v-for="tab in tabs"
        :key="tab.path"
        :to="{ name: tab.name }"
        class="nav-tab"
        active-class="active"
      >
        {{ tab.label }}
      </router-link>
    </div>

    <!-- 右侧：发布按钮 -->
    <div class="header-right">
      <el-button type="primary" class="publish-btn" @click="faBu">
        <el-icon><Upload /></el-icon>
        发布
      </el-button>
    </div>

    <el-dialog
      v-model="editDialogVisible"
      title="编辑应用"
      width="520px"
      class="app-edit-dialog"
      :close-on-click-modal="false"
      draggable
    >
      <div class="dialog-content">
        <el-form :model="appForm" label-position="top">
          <!-- 头像编辑 -->
          <div
            class="avatar-edit-container"
            @click.stop="openAvatarEditDialog"
          >
            <el-avatar
              :size="80"
              :src="appForm.avatar"
              class="avatar-preview"
            />
            <div class="avatar-edit-hint">
              <el-icon size="14"><Edit /></el-icon>
              <span>点击修改头像</span>
            </div>
          </div>
          <!-- 应用名称 -->
          <el-form-item label="应用名称" class="form-item" required>
            <el-input
              v-model="appForm.name"
              placeholder="请输入应用名称"
              clearable
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <!-- 应用模式 -->
          <el-form-item label="应用模式" class="form-item">
            <el-select
              v-model="appForm.mode"
              placeholder="请选择应用模式"
              class="mode-selector"
            >
              <el-option label="标准模式" value="standard" />
            </el-select>
            <div class="mode-description">
              <div class="mode-title">
                <el-icon size="14"><InfoFilled /></el-icon>
                <span>标准模式说明</span>
              </div>
              <p>回复更加精确和稳定，通过标准路径实现。</p>
              <p>适用于企业知识、产品说明等严肃问答场景。</p>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="saveAppInfo"
            :disabled="!appForm.name"
          >
            保存更改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑头像弹窗 -->
    <el-dialog
      v-model="avatarEditDialogVisible"
      title="修改应用头像"
      width="480px"
      class="avatar-edit-dialog"
      :close-on-click-modal="false"
      draggable
    >
      <div class="dialog-content">
        <div class="avatar-edit-options">
          <div class="option-section">
            <h4>上传新头像</h4>
            <el-upload
              class="avatar-uploader"
              drag
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload"
              accept=".jpg,.jpeg,.png,.webp"
            >
              <div class="uploader-content">
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div class="upload-text">
                  <p>点击或拖拽图片到此处</p>
                  <p class="upload-tip">
                    支持 JPG/PNG/WEBP 格式，大小不超过 500KB
                  </p>
                </div>
              </div>
            </el-upload>
          </div>

          <el-divider>
            <span class="divider-text">或</span>
          </el-divider>

          <div class="option-section">
            <h4>使用图片链接</h4>
            <div class="avatar-url-option">
              <el-input
                v-model="avatarUrl"
                placeholder="输入图片URL地址"
                clearable
                class="url-input"
              >
                <template #append>
                  <el-button
                    type="primary"
                    @click="confirmAvatarUrl"
                    :disabled="!avatarUrl"
                  >
                    确认
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref,computed } from "vue";
import { modifyApp } from "@/api/modules/auth";
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from "element-plus";
import bus from '@/bus/index.js'
const router = useRouter()
const props = defineProps({
  appData: {
    type: Object,
    required: true,
    default: () => ({})
  }
})

const appData = computed(() => props.appData);
// console.log(appData.value,'appDataappDataappData')

const tabs = ref([
  { path: "config", name: "ApplicationConfig", label: "应用管理" },
  { path: "knowledge", name: "KnowledgeMgmt", label: "知识管理" }
]);

const refreshPage = () => {
  router.go(0)
}

// 编辑表单
const appForm = ref({
  name: "",
  mode: "",
  avatar: "",
});

// 对话框状态
const editDialogVisible = ref(false);
const avatarEditDialogVisible = ref(false);
const avatarUrl = ref("");

// 打开编辑对话框
const openEditDialog = () => {
  appForm.value = {
    name: appData.value.BaseConfig.Name,
    mode: "standard",
    avatar: appData.value.BaseConfig.Avatar,
  };
  editDialogVisible.value = true;
};

// 打开头像编辑对话框
const openAvatarEditDialog = () => {
  avatarUrl.value = appForm.value.avatar;
  avatarEditDialogVisible.value = true;
};

// 保存应用信息
const saveAppInfo = async () => {
  console.log(appData.value,appForm.value);
  const BaseConfig = {
    Avatar:appForm.value.avatar,
    Name:appForm.value.name,
    Desc:""
  }
  const res = await modifyApp(appData.value.AppBizId,BaseConfig,appData.value.AppConfig);
  if(res.status == 200){
    editDialogVisible.value = false;
    ElMessage.success("应用信息已保存");
    refreshPage();
  }else{
    ElMessage.error("应用信息保存失败");
  }
};

// 确认头像URL
const confirmAvatarUrl = () => {
  if (!avatarUrl.value) return;

  // 简单验证URL格式
  if (!/^https?:\/\//i.test(avatarUrl.value)) {
    ElMessage.warning("请输入有效的图片URL，需包含http://或https://");
    return;
  }

  appForm.value.avatar = avatarUrl.value;
  avatarEditDialogVisible.value = false;
  ElMessage.success("头像已更新");
};

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const allowedTypes = ["image/jpeg", "image/png", "image/webp"];
  const isAllowedType = allowedTypes.includes(file.type);
  const isLt500KB = file.size / 1024 <= 500;

  if (!isAllowedType) {
    ElMessage.error("只能上传 JPG/PNG/WEBP 格式的图片!");
    return false;
  }
  if (!isLt500KB) {
    ElMessage.error("图片大小不能超过500KB!");
    return false;
  }
  return true;
};

const faBu = () => {
  bus.emit(`faBuZsMx`)
};

// 处理头像上传
const handleAvatarUpload = async (options) => {
  const loading = ElLoading.service({
    lock: true,
    text: "头像上传中...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    // 模拟上传过程
    await new Promise((resolve) => setTimeout(resolve, 1500));

    // 实际项目中这里应该是上传API调用
    // const formData = new FormData()
    // formData.append('file', options.file)
    // const response = await uploadAvatar(formData)

    // 模拟返回的URL
    const mockUrl = ``;
    appForm.value.avatar = mockUrl;
    avatarUrl.value = mockUrl;

    ElMessage.success("头像上传成功");
    avatarEditDialogVisible.value = false;
  } catch (error) {
    ElMessage.error("头像上传失败: " + error.message);
  } finally {
    loading.close();
  }
};
</script>

<style scoped lang="scss">
/* 主头部样式保持不变 */
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 56px;
  padding: 0 24px;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.home-link {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  font-size: 20px;
  text-decoration: none;
  transition: color 0.3s;
}

.home-link:hover {
  color: #409eff;
}

.app-avatar {
  cursor: pointer;
  transition: transform 0.3s;
}

.app-avatar:hover {
  transform: scale(1.05);
}

.app-info {
  display: flex;
  flex-direction: column;
  line-height: 1.2;
}

.app-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.app-mode {
  font-size: 12px;
  color: #909399;
}

.header-center {
  display: flex;
  justify-content: center;
  flex: 2;
}

.nav-tab {
  display: flex;
  align-items: center;
  padding: 0 16px;
  font-size: 14px;
  color: #606266;
  text-decoration: none;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.nav-tab:hover {
  color: #409eff;
}

.nav-tab.active {
  color: #409eff;
  border-bottom-color: #409eff;
  font-weight: 500;
}

.header-right {
  display: flex;
  justify-content: flex-end;
  flex: 1;
}

.publish-btn {
  padding: 8px 16px;
}

/* 编辑应用弹窗样式 */
:deep(.app-edit-dialog) {
  border-radius: 8px;
  
  .el-dialog__header {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f2f5;
    margin-right: 0;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    padding: 16px 20px;
    
    .form-item {
      margin-bottom: 20px;
      
      .el-form-item__label {
        font-size: 13px;
        font-weight: 500;
        padding-bottom: 6px;
        color: #606266;
      }
    }
    
    .avatar-edit-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      
      .avatar-edit-hint {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 13px;
        color: #606266;
      }
    }
    
    .mode-selector {
      width: 100%;
    }
    
    .mode-description {
      margin-top: 12px;
      padding: 12px;
      background-color: #f7f8fa;
      border-radius: 6px;
      font-size: 13px;
      line-height: 1.6;
      width: 100%;
      .mode-title {
        display: flex;
        align-items: center;
        gap: 6px;
        margin-bottom: 8px;
        font-weight: 500;
      }
    }
  }
  
  .dialog-footer {
    padding: 12px 20px;
    border-top: 1px solid #f0f2f5;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    
    .el-button {
      min-width: 80px;
      padding: 8px 16px;
    }
  }
}

/* 头像编辑弹窗样式 */
:deep(.avatar-edit-dialog) {
  border-radius: 12px;
  overflow: hidden;

  .el-dialog__header {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f2f5;
    margin-right: 0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #1d2129;
    }

    .el-dialog__headerbtn {
      top: 22px;
    }
  }

  .dialog-content {
    padding: 20px 24px;

    .avatar-edit-options {
      display: flex;
      flex-direction: column;
      gap: 20px;

      .option-section {
        h4 {
          margin: 0 0 12px 0;
          font-size: 15px;
          font-weight: 500;
          color: #1d2129;
        }
      }

      .el-divider {
        margin: 16px 0;

        .divider-text {
          color: #86909c;
          font-size: 13px;
          padding: 0 12px;
          background: white;
        }
      }

      .avatar-uploader {
        .el-upload-dragger {
          padding: 24px;
          width: 100%;
          height: 180px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          border-radius: 8px;

          .uploader-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 12px;

            .upload-icon {
              font-size: 32px;
              color: #409eff;
            }

            .upload-text {
              text-align: center;
              font-size: 14px;
              color: #606266;

              .upload-tip {
                font-size: 12px;
                color: #909399;
                margin-top: 4px;
              }
            }
          }
        }
      }

      .avatar-url-option {
        .url-input {
          .el-input-group__prepend {
            padding: 0 12px;
            color: #606266;
          }
        }
      }
    }
  }
}
</style>